﻿using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using HsServerHa.Entity;
using HsServerHa.ViewModel.SqlserverMirrorViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HsServerHa.Utility.FileHelper;
using HsServerHa.Utility.SQLite;
using HsServerHa.Entity.Models;
using System.Configuration;
using Newtonsoft.Json;
using HsServerHa.Utility.HttpHelper;
using HsServerHa.Core.Http;
using HsServerHa.Utility.SqlserverMirror;

namespace HsServerHa.UserControls.SqlserverMirrorControls.CheckConfigurations
{
    /// <summary>
    /// CheckConfiguration.xaml 的交互逻辑
    /// </summary>
    public partial class CheckConfiguration : Page
    {
        public CheckConfiguration()
        {
            InitializeComponent();
            Tag = new PageInfo(PageState.MidPage, 2);

            leftServer = ((SingleCheckViewModel)this.LeftCheck.DataContext);
            rightServer = ((SingleCheckViewModel)this.RightCheck.DataContext);
            leftServer.SerInfo.ServerName = ParameterSettings.LeftServer;
            rightServer.SerInfo.ServerName = ParameterSettings.RightServer;
            leftServer.SerInfo.DBConnectStr = ParameterSettings.LeftDataBaseConnection;
            rightServer.SerInfo.DBConnectStr = ParameterSettings.RightDataBaseConnection;
            leftServer.SerInfo.HostName = "HOST_1";
            rightServer.SerInfo.HostName = "HOST_2";
            //this.OperateButton.Content = "重新配置镜像";


            var dbBackFilePathEntity=SQLiteHelper.Table<DbBackFilePathEntity>().FirstOrDefault();
            if (dbBackFilePathEntity != null)
            {
                this.FolderPath.Text = dbBackFilePathEntity.FilePath;
            }
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            ButtonReset();
        }

        SingleCheckViewModel leftServer;
        SingleCheckViewModel rightServer;

        private bool SettingFolderPath()
        {
            try
            {
                if (!FileHelpers.CreateDic(FolderPath.Text))
                {
                    MessageBox.Show($"文件路径：{this.FolderPath.Text}，创建失败！");
                    return false;
                }
                SQLiteHelper.ExecuteSql($"delete from  DbBackFilePath");
                var parms = new DbBackFilePathEntity
                {
                    FilePath = this.FolderPath.Text,
                    UpdateTime = DateTime.Now.ToString()
                };
                SQLiteHelper.ExecuteSql($"insert into DbBackFilePath (FilePath,UpdateTime)" +
                                         $" values('{parms.FilePath}','{parms.UpdateTime}')");
                //同步文件夹路径
                var slavePath = $"http://{rightServer.SerInfo.ServerName}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                var result = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(slavePath +
               (ConfigurationManager.AppSettings["syncDbBackPath"]?.ToString() ?? "syncDbBackPath"), JsonConvert.SerializeObject(new DbBackFilePathEntity { FilePath = FolderPath.Text }));
                if (result != null && result.Result.IsSuccess == true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }

        }
        private void ButtonReset()
        {
            if (CheckResult.Content == null) return;
            if (CheckResult.Content.ToString() == "检查通过")
            {
                if (string.IsNullOrEmpty(this.FolderPath.Text))
                {
                    MessageBox.Show("请选择数据库配置路径！");
                    return;
                }
                else
                {
                    if (!FileHelpers.CreateDic(FolderPath.Text))
                    {
                        MessageBox.Show($"文件路径：{this.FolderPath.Text}，创建失败！");
                        return;
                    }
                }
                ParameterSettings.FolderPath = FolderPath.Text;
                WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>("启用"), "NextButtonIsEnable");
            }
            else
            {
                WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>("禁用"), "NextButtonIsEnable");
            }


        }

        private void AduFlatButton_Click(object sender, RoutedEventArgs e)
        {


            bool leftOp = false, rightOp = false;

            switch (this.OperateButton.Content.ToString())
            {
                case "检查配置项":
                    leftOp = leftServer.DBCheck();
                    rightOp = rightServer.DBCheck();
                    if (leftOp && rightOp)
                    {
                        CheckResult.Content = "检查通过";
                        CheckResult.Foreground = Brushes.Green;

                    }
                    else
                    {
                        CheckResult.Content = "配置检测失败！请重新配置镜像！";
                        CheckResult.Foreground = Brushes.Red;
                        this.OperateButton.Content = "重新配置镜像";
                    }
                    break;
                case "重新配置镜像":
                    var result=SettingFolderPath();//设置文件夹路径
                    if (!result)
                    {
                        CheckResult.Content = "创建文件夹报错，请检查文件路径在主从机上是否存在";
                        CheckResult.Foreground = Brushes.Red;
                        return;
                    }
                    leftOp = leftServer.ResetMirror(this.FolderPath.Text);
                    rightOp = rightServer.ResetMirror(this.FolderPath.Text);

                    if (leftOp && rightOp)
                    {
                        
                        //同步证书文件
                        var masterSlaveBindEntity = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList().FirstOrDefault();
                        if (masterSlaveBindEntity != null)
                        {
                            //获取db备份文件保存路径
                            var dbBackFilePathEntity = SQLiteHelper.Table<DbBackFilePathEntity>().ToList().FirstOrDefault();
                            string dbBackFolder = @"d:\\dbback";
                            if (dbBackFilePathEntity != null)
                            {
                                dbBackFolder = dbBackFilePathEntity.FilePath;
                            }
                            //同步证书到从机
                            CheckStatementCommand.SyncCertificateToSlaveServer(masterSlaveBindEntity.SlaveIP, dbBackFolder);
                            //同步证书到主机
                            CheckStatementCommand.SyncCertificateToHostServer(masterSlaveBindEntity.MasterIP, masterSlaveBindEntity.SlaveIP, dbBackFolder);
                        }
                        CheckResult.Content = "证书文件(.cer文件)交换完成";
                        CheckResult.Foreground = Brushes.Green;
                        this.OperateButton.Content = "配置出站";
                    }
                    else
                    {
                        CheckResult.Content = "初始化配置失败!请联系开发人员处理";
                        CheckResult.Foreground = Brushes.Red;
                    }
                    break;
                //case "配置入站":
                //    leftOp = leftServer.ResetMirror(this.FolderPath.Text);
                //    rightOp = rightServer.ResetMirror(this.FolderPath.Text);
                //    if (leftOp && rightOp)
                //    {
                //        CheckResult.Content = $"请将证书文件(.cer文件)拷贝到对方相应目录下！";
                //        CheckResult.Foreground = Brushes.Yellow;
                //    }
                //    break;
                case "配置出站":
                    leftOp = leftServer.ImportCertificate(this.FolderPath.Text);
                    rightOp = rightServer.ImportCertificate(this.FolderPath.Text);
                    if (leftOp && rightOp)
                    {
                        CheckResult.Content = "检查通过";
                        CheckResult.Foreground = Brushes.Green;
                        this.OperateButton.IsEnabled = false;

                    }
                    else
                    {
                        CheckResult.Content = "配置出站失败！";
                        CheckResult.Foreground = Brushes.Red;
                        this.OperateButton.Content = "配置出站";
                    }
                    break;
            }
            ButtonReset();
        }
    }
}
